package com.inputabc.ct.v1.ui;

import com.inputabc.ct.v1.context.Components;
import com.inputabc.ct.v1.context.ComponentsBuilder;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TranslationHistoryDialog {
    private Components translationHistoryDialogComponents = ComponentsBuilder.getComponentsContext()
            .get(TranslationHistoryDialog.class);
    
    private JDialog dialog;
    private JPanel mainPanel;
    private JTable historyTable;
    private DefaultTableModel tableModel;
    private JScrollPane scrollPane;
    private JButton clearButton;
    private JButton exportButton;
    private JButton closeButton;
    
    // 历史记录数据
    private List<TranslationRecord> historyRecords = new ArrayList<>();
    
    // 历史记录文件
    private static final String HISTORY_FILE = "translation_history.txt";
    
    public TranslationHistoryDialog(JFrame parent) {
        // 创建对话框
        dialog = new JDialog(parent, "翻译历史记录", true);
        
        // 初始化界面
        initUI();
        
        // 加载历史记录
        loadHistoryFromFile();
        
        // 设置对话框属性
        dialog.setSize(800, 500);
        dialog.setLocationRelativeTo(parent);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    }
    
    private void initUI() {
        // 主面板
        mainPanel = new JPanel(new BorderLayout(5, 5));
        
        // 表格模型
        String[] columnNames = {"时间", "原文", "译文", "翻译方向", "翻译引擎"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 不可编辑
            }
        };
        
        // 创建表格
        historyTable = new JTable(tableModel);
        historyTable.getColumnModel().getColumn(0).setPreferredWidth(150);
        historyTable.getColumnModel().getColumn(1).setPreferredWidth(250);
        historyTable.getColumnModel().getColumn(2).setPreferredWidth(250);
        historyTable.getColumnModel().getColumn(3).setPreferredWidth(100);
        historyTable.getColumnModel().getColumn(4).setPreferredWidth(100);
        
        // 添加鼠标点击监听器
        historyTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount()==2) {
                    int row = historyTable.rowAtPoint(e.getPoint());
                    int col = historyTable.columnAtPoint(e.getPoint());

                    // 只处理原文和译文列的点击
                    if (row >= 0 && (col == 1 || col == 2)) {
                        String content = (String) historyTable.getValueAt(row, col);
                        showPreviewDialog(content, col == 1 ? "原文" : "译文");
                    }
                }
            }
        });
        
        // 添加到滚动面板
        scrollPane = new JScrollPane(historyTable);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        
        // 清空按钮
        clearButton = new JButton("清空记录");
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int result = JOptionPane.showConfirmDialog(dialog, 
                        "确定要清空所有历史记录吗？此操作无法撤销。", 
                        "确认", JOptionPane.YES_NO_OPTION);
                
                if (result == JOptionPane.YES_OPTION) {
                    clearHistory();
                }
            }
        });
        
        // 导出按钮
        exportButton = new JButton("导出记录");
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                exportHistory();
            }
        });
        
        // 关闭按钮
        closeButton = new JButton("关闭");
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveHistoryToFile();
                dialog.dispose();
            }
        });
        
        buttonPanel.add(exportButton);
        buttonPanel.add(clearButton);
        buttonPanel.add(closeButton);
        
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 设置对话框内容面板
        dialog.setContentPane(mainPanel);
    }
    
    /**
     * 添加翻译记录
     * @param sourceText 原文
     * @param targetText 译文
     * @param translationDirection 翻译方向
     * @param translationEngine 翻译引擎
     */
    public void addTranslationRecord(String sourceText, String targetText, 
                                     String translationDirection, String translationEngine) {
        // 创建一条新记录
        TranslationRecord record = new TranslationRecord(
            new Date(), sourceText, targetText, translationDirection, translationEngine
        );
        
        // 添加到记录列表
        historyRecords.add(0, record); // 新记录添加到最前面
        
        // 更新表格
        updateTableModel();
        
        // 保存到文件
        saveHistoryToFile();
    }
    
    /**
     * 清空历史记录
     */
    private void clearHistory() {
        historyRecords.clear();
        updateTableModel();
        
        // 清空文件
        saveHistoryToFile();
    }
    
    /**
     * 更新表格模型
     */
    private void updateTableModel() {
        // 清空表格
        tableModel.setRowCount(0);
        
        // 添加所有记录
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (TranslationRecord record : historyRecords) {
            String time = dateFormat.format(record.getTime());
            String sourceText = record.getSourceText();
            String targetText = record.getTargetText();
            String translationDirection = record.getTranslationDirection();
            String translationEngine = record.getTranslationEngine();
            
            tableModel.addRow(new Object[]{time, sourceText, targetText, translationDirection, translationEngine});
        }
    }
    
    /**
     * 显示对话框
     */
    public void setVisible(boolean visible) {
        if (visible) {
            updateTableModel();
        }
        dialog.setVisible(visible);
    }
    
    /**
     * 导出历史记录
     */
    private void exportHistory() {
        if (historyRecords.isEmpty()) {
            JOptionPane.showMessageDialog(dialog, "没有历史记录可导出", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        try {
            File file = new File("translation_history_export.txt");
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            
            writer.write("CT Cat 翻译历史记录\r\n");
            writer.write("导出时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\r\n");
            writer.write("==========================================================\r\n\r\n");
            
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (TranslationRecord record : historyRecords) {
                writer.write("时间: " + dateFormat.format(record.getTime()) + "\r\n");
                writer.write("原文: " + record.getSourceText() + "\r\n");
                writer.write("译文: " + record.getTargetText() + "\r\n");
                writer.write("翻译方向: " + record.getTranslationDirection() + "\r\n");
                writer.write("翻译引擎: " + record.getTranslationEngine() + "\r\n");
                writer.write("----------------------------------------------------------\r\n");
            }
            
            writer.close();
            
            JOptionPane.showMessageDialog(dialog, 
                    "历史记录已导出到文件：" + file.getAbsolutePath(), 
                    "导出成功", JOptionPane.INFORMATION_MESSAGE);
            
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(dialog, 
                    "导出失败: " + e.getMessage(), 
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 将历史记录保存到文件
     */
    private void saveHistoryToFile() {
        try {
            System.out.println("保存历史记录到文件: " + HISTORY_FILE);
            
            // 创建文件
            File file = new File(HISTORY_FILE);
            if (!file.exists()) {
                file.createNewFile();
            }
            
            // 使用UTF-8编码写入文件
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            
            // 写入记录数量
            writer.write(historyRecords.size() + "\r\n");
            
            // 写入每条记录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (TranslationRecord record : historyRecords) {
                // 时间
                writer.write(dateFormat.format(record.getTime()) + "\r\n");
                // 原文
                writer.write(escapeNewlines(record.getSourceText()) + "\r\n");
                // 译文
                writer.write(escapeNewlines(record.getTargetText()) + "\r\n");
                // 翻译方向
                writer.write(record.getTranslationDirection() + "\r\n");
                // 翻译引擎
                writer.write(record.getTranslationEngine() + "\r\n");
            }
            
            writer.close();
            System.out.println("历史记录已保存，共 " + historyRecords.size() + " 条");
            
        } catch (Exception e) {
            System.err.println("保存历史记录失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 从文件加载历史记录
     */
    private void loadHistoryFromFile() {
        historyRecords.clear();
        
        try {
            File file = new File(HISTORY_FILE);
            if (!file.exists()) {
                System.out.println("历史记录文件不存在");
                return;
            }
            
            // 使用UTF-8编码读取文件
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            
            // 读取记录数量
            String countLine = reader.readLine();
            if (countLine == null) {
                reader.close();
                return;
            }
            
            int count = Integer.parseInt(countLine);
            System.out.println("加载历史记录，共 " + count + " 条");
            
            // 读取每条记录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < count; i++) {
                String timeLine = reader.readLine();
                String sourceText = unescapeNewlines(reader.readLine());
                String targetText = unescapeNewlines(reader.readLine());
                String translationDirection = reader.readLine();
                String translationEngine = reader.readLine();
                
                if (timeLine == null || sourceText == null || targetText == null || 
                    translationDirection == null || translationEngine == null) {
                    break;
                }
                
                Date time = dateFormat.parse(timeLine);
                
                TranslationRecord record = new TranslationRecord(
                    time, sourceText, targetText, translationDirection, translationEngine
                );
                
                historyRecords.add(record);
            }
            
            reader.close();
            
        } catch (Exception e) {
            System.err.println("加载历史记录失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 转义换行符，保存到文件时使用
     */
    private String escapeNewlines(String text) {
        if (text == null) return "";
        return text.replace("\n", "\\n").replace("\r", "\\r");
    }
    
    /**
     * 反转义换行符，从文件读取时使用
     */
    private String unescapeNewlines(String text) {
        if (text == null) return "";
        return text.replace("\\n", "\n").replace("\\r", "\r");
    }
    
    /**
     * 显示预览对话框
     * @param content 要显示的内容
     * @param title 对话框标题
     */
    private void showPreviewDialog(String content, String title) {
        // 创建预览对话框
        JDialog previewDialog = new JDialog(dialog, title, true);
        previewDialog.setSize(400, 300);
        previewDialog.setLocationRelativeTo(dialog);
        
        // 添加标题栏双击最大化功能
        previewDialog.addMouseListener(new MouseAdapter() {
            private Dimension originalSize = previewDialog.getSize();
            private Point originalLocation = previewDialog.getLocation();
            
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2 && e.getY() < 30) { // 双击标题栏区域
                    if (previewDialog.getSize().equals(Toolkit.getDefaultToolkit().getScreenSize())) {
                        // 如果已经是最大化状态，则恢复到原始大小
                        previewDialog.setSize(originalSize);
                        previewDialog.setLocation(originalLocation);
                    } else {
                        // 保存当前位置和大小，然后最大化
                        originalSize = previewDialog.getSize();
                        originalLocation = previewDialog.getLocation();
                        previewDialog.setSize(Toolkit.getDefaultToolkit().getScreenSize());
                        previewDialog.setLocation(0, 0);
                    }
                }
            }
        });
        
        // 创建文本区域
        JTextArea textArea = new JTextArea(content);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 添加到滚动面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        previewDialog.add(scrollPane);
        
        // 显示对话框
        previewDialog.setVisible(true);
    }
    
    /**
     * 内部类：翻译记录
     */
    private static class TranslationRecord {
        private Date time;
        private String sourceText;
        private String targetText;
        private String translationDirection;
        private String translationEngine;
        
        public TranslationRecord(Date time, String sourceText, String targetText, 
                                String translationDirection, String translationEngine) {
            this.time = time;
            this.sourceText = sourceText;
            this.targetText = targetText;
            this.translationDirection = translationDirection;
            this.translationEngine = translationEngine;
        }
        
        public Date getTime() {
            return time;
        }
        
        public String getSourceText() {
            return sourceText;
        }
        
        public String getTargetText() {
            return targetText;
        }
        
        public String getTranslationDirection() {
            return translationDirection;
        }
        
        public String getTranslationEngine() {
            return translationEngine;
        }
    }
} 